/*
 * IfNode.cpp
 *
 *  Created on: 28/dic/2010
 *      Author: computer
 */

#include "DerivationTree.h"
#include "WhileInstruction.h"

WhileNode::WhileNode() : NodeTree_CRTP<WhileNode>() { }

WhileNode::WhileNode(const WhileNode& copy) : NodeTree_CRTP<WhileNode>(copy), condition(copy.condition), listInstruction(copy.listInstruction) { }

void WhileNode::setCondition(const AutoPointer<NodeTree>& _condition) {
	condition = _condition;
}

void WhileNode::addInstruction(const AutoPointer<NodeTree>& instruction) {
	listInstruction.push_back(instruction);
}

bool WhileNode::execute(Pointer<LeonardVirtualMachine> LVM) {
	condition->execute(LVM);
	TreeExpression::WhileInstruction* ris = new TreeExpression::WhileInstruction();
	std::list< AutoPointer<NodeTree> >::reverse_iterator j;
	for (j = listInstruction.rbegin(); j != listInstruction.rend(); ++j) {
		(*j)->execute(LVM);//Load the instruction
		ris->addInstruction(LVM->top());
		LVM->pop();
	}
	ris->setCondition(LVM->top());//set the condition
	LVM->pop();
	LVM->push(AutoPointer<TreeExpression::Expression>(ris));
	return true;
}
